<template>
  <div class="home-container">
    <div class="hero-section cartoon-hero">
      <div class="hero-content ctn-bubble">
        <h1 class="hero-title ctn-title">🎨 涂色抢地盘</h1>
        <p class="hero-subtitle">多人实时涂色竞技游戏</p>
        <p class="hero-description">与朋友一起在画布上涂色，占领最大面积获得胜利！</p>
      </div>
    </div>

    <!-- 波浪分割装饰 -->
    <div class="hero-wave" aria-hidden="true">
      <svg viewBox="0 0 1440 120" preserveAspectRatio="none">
        <path d="M0,32L60,53.3C120,75,240,117,360,117.3C480,117,600,75,720,53.3C840,32,960,32,1080,32C1200,32,1320,32,1380,32L1440,32L1440,120L1380,120C1320,120,1200,120,1080,120C960,120,840,120,720,120C600,120,480,120,360,120C240,120,120,120,60,120L0,120Z" fill="#ffffff"/>
      </svg>
    </div>

    <div class="main-content">
      <!-- 排行榜 -->
      <Leaderboard />
      
      <div class="action-tabs ctn-card">
        <el-tabs v-model="homeTab" class="ctn-tabs" stretch>
          <el-tab-pane label="创建房间" name="create">
            <transition name="tab-fade-slide" mode="out-in">
            <div class="card-content" v-if="homeTab === 'create'">
              <el-form :model="createForm" :rules="createRules" ref="createFormRef" class="ctn-form">
                <el-form-item prop="roomName" label="房间名称">
                  <el-input 
                    v-model="createForm.roomName" 
                    placeholder="输入房间名称"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
                
                <el-form-item prop="nickname" label="你的昵称">
                  <el-input 
                    v-model="createForm.nickname" 
                    placeholder="输入你的昵称"
                    maxlength="15"
                    show-word-limit
                  />
                </el-form-item>
                
                <el-form-item prop="maxPlayers" label="最大玩家数">
                  <el-select v-model="createForm.maxPlayers" placeholder="选择玩家数量">
                    <el-option label="2人" :value="2" />
                    <el-option label="3人" :value="3" />
                    <el-option label="4人" :value="4" />
                    <el-option label="5人" :value="5" />
                    <el-option label="6人" :value="6" />
                  </el-select>
                </el-form-item>
                
                <el-form-item prop="password" label="房间密码（可选）">
                  <el-input 
                    v-model="createForm.password" 
                    placeholder="设置房间密码"
                    type="password"
                    show-password
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="createRoom"
                    :loading="creating"
                    class="action-button ctn-btn-primary"
                  >
                    创建房间
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            </transition>
          </el-tab-pane>
          
          <el-tab-pane label="加入房间" name="join">
            <transition name="tab-fade-slide" mode="out-in">
            <div class="card-content" v-if="homeTab === 'join'">
              <el-form :model="joinForm" :rules="joinRules" ref="joinFormRef" class="ctn-form">
                <el-form-item prop="roomCode" label="房间代码">
                  <el-input 
                    v-model="joinForm.roomCode" 
                    placeholder="输入6位房间代码"
                    maxlength="6"
                    show-word-limit
                  />
                </el-form-item>
                
                <el-form-item prop="nickname" label="你的昵称">
                  <el-input 
                    v-model="joinForm.nickname" 
                    placeholder="输入昵称"
                    maxlength="15"
                    show-word-limit
                  />
                </el-form-item>
                
                <el-form-item prop="password" label="房间密码">
                  <el-input 
                    v-model="joinForm.password" 
                    placeholder="输入房间密码（如果有）"
                    type="password"
                    show-password
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="success" 
                    @click="joinRoom"
                    :loading="joining"
                    class="action-button ctn-btn-success"
                  >
                    加入房间
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
            </transition>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <div class="feature-cards">
        <div class="feature-card ctn-card">
          <div class="card-header">
            <h3>历史记录</h3>
          </div>
          <div class="card-content">
            <p>查看最近的对局结果与玩家排名</p>
            <el-button 
              type="info" 
              @click="goToHistory"
              class="feature-button ctn-btn-info"
            >
              查看历史
            </el-button>
          </div>
        </div>
      </div>
      
      
    </div>

    <!-- 加载提示 -->
    <div v-loading="loading" 
         element-loading-text="正在处理..."
         element-loading-background="rgba(0, 0, 0, 0.7)"
         element-loading-spinner="el-icon-loading">
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User } from '@element-plus/icons-vue'
import { useGameStore } from '@/stores/game'
import { useAuthStore } from '@/stores/auth'
import { createSignalRService } from '@/services/socketService'
import Leaderboard from '@/components/Leaderboard.vue'

const router = useRouter()
const gameStore = useGameStore()
const auth = useAuthStore()

// 表单引用
const createFormRef = ref()
const joinFormRef = ref()

// 状态
const creating = ref(false)
const joining = ref(false)
const loading = ref(false)
const homeTab = ref('create')

// 创建房间表单
const createForm = reactive({
  roomName: '',
  nickname: '',
  maxPlayers: 6,
  password: ''
})

// 加入房间表单
const joinForm = reactive({
  roomCode: '',
  nickname: '',
  password: ''
})

// 表单验证规则
const createRules = {
  roomName: [
    { required: true, message: '请输入房间名称', trigger: 'blur' },
    { min: 2, max: 20, message: '房间名称长度在2-20个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 15, message: '昵称长度在2-15个字符', trigger: 'blur' }
  ],
  maxPlayers: [
    { required: true, message: '请选择最大玩家数', trigger: 'change' }
  ]
}

const joinRules = {
  roomCode: [
    { required: true, message: '请输入房间代码', trigger: 'blur' },
    { len: 6, message: '房间代码必须是6位', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 15, message: '昵称长度在2-15个字符', trigger: 'blur' }
  ]
}

// 延迟在创建/加入房间时初始化连接

// 创建房间
async function createRoom() {
  try {
    if (!auth.token) {
      ElMessage.warning('请先登录')
      router.push('/')
      return
    }
    await createFormRef.value.validate()
    
    creating.value = true
    loading.value = true
    
    // 生成房间代码
    const roomCode = generateRoomCode()
    
    // 创建玩家信息（颜色将由后端自动分配）
    const player = {
      id: generatePlayerId(),
      nickname: createForm.nickname || '房主',
      color: '', // 颜色将由后端自动分配
      isOwner: true
    }
    
    // 设置当前玩家
    gameStore.setCurrentPlayer(player)
    
    // 连接到SignalR
    const signalRService = createSignalRService(gameStore)
    await signalRService.connect()
    
    // 创建房间（不传递颜色，让后端自动分配）
    await signalRService.createRoom(
      roomCode,
      createForm.roomName,
      Number(createForm.maxPlayers),
      createForm.password,
      player.id,
      player.nickname
    )
    
    ElMessage.success(`房间创建成功！房间代码：${roomCode}`)
    
    // 跳转到房间页面
    router.push(`/room/${roomCode}`)
    
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建房间失败，请重试')
    }
  } finally {
    creating.value = false
    loading.value = false
  }
}

// 加入房间
async function joinRoom() {
  try {
    if (!auth.token) {
      ElMessage.warning('请先登录')
      router.push('/')
      return
    }
    await joinFormRef.value.validate()
    
    joining.value = true
    loading.value = true
    
    // 创建玩家信息（颜色将由后端自动分配）
    const player = {
      id: generatePlayerId(),
      nickname: joinForm.nickname,
      color: '', // 颜色将由后端自动分配
      isOwner: false
    }
    
    // 设置当前玩家
    gameStore.setCurrentPlayer(player)
    
    // 连接到SignalR
    const signalRService = createSignalRService(gameStore)
    await signalRService.connect()
    
    // 加入房间（不传递颜色，让后端自动分配）
    await signalRService.joinRoom(
      joinForm.roomCode,
      player.id,
      player.nickname,
      joinForm.password
    )
    
    ElMessage.success('成功加入房间！')
    
    // 跳转到房间页面
    router.push(`/room/${joinForm.roomCode}`)
    
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('加入房间失败，请重试')
    }
  } finally {
    joining.value = false
    loading.value = false
  }
}

 



// 生成6位房间代码
function generateRoomCode() {
  return Math.random().toString(36).substring(2, 8).toUpperCase()
}

// 生成玩家ID
function generatePlayerId() {
  return 'player_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8)
}

function goToHistory() {
  router.push('/history')
}

// 生成随机颜色
function generateRandomColor() {
  const colors = [
    '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', 
    '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

function goToAuth() {
  router.push('/')
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.hero-section {
  padding: 80px 20px;
  text-align: center;
  color: white;
}

.hero-wave { margin-top: -20px; }
.hero-wave svg { display: block; width: 100%; height: 80px; }

/* 卡通英雄区增强 */
.cartoon-hero {
  position: relative;
  background: radial-gradient(800px 400px at 10% 20%, #ffe9f6 0%, rgba(255,233,246,0) 60%),
              radial-gradient(800px 400px at 90% 10%, #e9f6ff 0%, rgba(233,246,255,0) 60%);
}

.cartoon-hero::before,
.cartoon-hero::after {
  content: "";
  position: absolute;
  pointer-events: none;
  filter: drop-shadow(0 10px 18px rgba(0,0,0,0.08));
}

.cartoon-hero::before {
  width: 140px;
  height: 140px;
  left: 6%;
  top: 24px;
  background: conic-gradient(from 180deg, #ffd8ef, #fff 60%);
  border-radius: 40% 60% 50% 50% / 50% 40% 60% 50%;
  animation: floatY 5s ease-in-out infinite;
}

.cartoon-hero::after {
  width: 110px;
  height: 110px;
  right: 8%;
  top: 60px;
  background: conic-gradient(from 0deg, #dff2ff, #fff 65%);
  border-radius: 60% 40% 50% 50% / 50% 60% 40% 50%;
  animation: floatY 6s ease-in-out -1s infinite;
}

.hero-title {
  font-size: 3.5rem;
  font-weight: bold;
  margin: 0 0 20px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.hero-content.ctn-bubble {
  display: inline-block;
  padding: 24px 28px;
}

.hero-subtitle {
  font-size: 1.5rem;
  margin: 0 0 15px 0;
  opacity: 0.9;
}

.hero-description {
  font-size: 1.1rem;
  margin: 0;
  opacity: 0.8;
  max-width: 600px;
  margin: 0 auto;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.action-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 40px;
  margin-bottom: 60px;
}

.action-tabs {
  margin-bottom: 60px;
  padding: 12px;
}

/* 选项卡切换过渡 */
.tab-fade-slide-enter-active,
.tab-fade-slide-leave-active {
  transition: opacity 260ms cubic-bezier(0.22, 1, 0.36, 1),
              transform 260ms cubic-bezier(0.22, 1, 0.36, 1);
}
.tab-fade-slide-enter-from,
.tab-fade-slide-leave-to {
  opacity: 0;
  transform: translateY(8px) scale(0.99);
}

.action-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
}

.action-card:hover {
  transform: translateY(-6px) scale(1.01) rotate(-0.3deg);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.action-card.ctn-card::after,
.feature-card.ctn-card::after {
  content: "";
  position: absolute;
  right: 16px;
  top: 16px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, #ffd166, #ff7ac3);
  box-shadow: 0 0 0 6px rgba(255, 122, 195, 0.08), 16px 8px 0 0 rgba(122,211,255,0.15), -14px 10px 0 0 rgba(255,209,102,0.15);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.card-icon {
  font-size: 2rem;
  color: #1890ff;
}

.card-header h3 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.card-content {
  color: #666;
}

.action-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
}

.action-button:hover,
.feature-button:hover {
  transform: translateY(-2px);
  transition: transform 0.15s ease;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  margin-top: 60px;
}

.feature-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  text-align: center;
  position: relative;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.feature-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
}

@keyframes floatY {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.game-instructions {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.game-instructions h3 {
  text-align: center;
  font-size: 2rem;
  color: #333;
  margin: 0 0 40px 0;
}

.instructions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 30px;
}

.instruction-item {
  text-align: center;
  padding: 20px;
}

.instruction-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.instruction-item h4 {
  font-size: 1.2rem;
  color: #333;
  margin: 0 0 10px 0;
}

.instruction-item p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

@media (max-width: 768px) {
  .hero-title {
    font-size: 2.5rem;
  }
  
  .hero-subtitle {
    font-size: 1.2rem;
  }
  
  .action-cards {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .action-card {
    padding: 20px;
  }
  
  .game-instructions {
    padding: 20px;
  }
  
  .instructions-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}
</style>
